<?php
/**
 * Created by PhpStorm.
 * User: mayn
 * Date: 2018/8/27
 * Time: 11:09
 */

namespace app\api\models;

use app\api\core\CreateUuid;
use app\api\core\wechat\wxAction;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use phpDocumentor\Reflection\Types\Self_;
use spec\Prophecy\Argument\Token\LogicalAndTokenSpec;
use Yii;
use Cm;
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;
use yii\log\EmailTarget;

class AnalysisModel extends BaseModel
{
    public function actionUserReport()
    {

        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);
        $begin_date = Cm::$req->post('begin_date', ['reg'=>'/^\d{4}-\d{2}-\d{2}/', 'title'=>'开始时间', 'null', 'empty', 'default'=>null]);
        $end_date = Cm::$req->post('end_date', ['reg'=>'/^\d{4}-\d{2}-\d{2}/', 'title'=>'结束时间', 'null', 'empty', 'default'=>null]);
        $timer = Cm::$req->post('timer', ['reg'=>'/[a-z_].+/', 'title'=>'时间区间', 'null', 'empty']);
        $user_source = Cm::$req->post('user_source', ['reg'=>'/^\w+/', 'title'=>'粉丝来源', 'null', 'empty']);
        $type = Cm::$req->post('type', ['reg'=>'/[a-z_]+/', 'title'=>'统计类型', 'null', 'empty']);



        if ($timer && !in_array($timer, ['yesterday', 'nearly_a_week', 'nearly_a_month'])) {
            Cm::$res->error('参数timer不符合规则');
        } else {
            if (!empty($begin_date)) {
                if (strtotime($begin_date) > time()) {
                    Cm::$res->error('开始时间小于当前时间');
                }

                if (!empty($end_date)) {
                    if (strtotime($end_date) > time()) {
                        Cm::$res->error('结束时间小于当前时间');
                    }
                } else {
                    Cm::$res->error('请传入结束时间');
                }
            }
        }
        $typeFlag = [
            'new_user'=>'subscribe',
            'cancel_user'=>'unsubscribe',
            'clean_user'=>'subscribe',
            'cumulate_user'=>'subscribe'
        ];

        $where = null;
        if ($timer) {
            $date = self::getDate($timer);
            $begin_date = $date['start'];
            $end_date = $date['end'];
            if ($type=='cumulate_user') {
                $where = " AND {$typeFlag[$type]} <='{$date['end']}'";
            } else {
                $where = " AND {$typeFlag[$type]} BETWEEN '{$date['start']}' AND '{$date['end']}'";
            }

        } else {
            $begin_date = date('Y-m-d 00:00:00', strtotime($begin_date));
            $end_date = date('Y-m-d 23:59:59', strtotime($end_date));
            if ($begin_date && $end_date) {

                if ($type=='cumulate_user') {
                    $where = " AND {$typeFlag[$type]} <= '{$end_date}'";
                } else {
                    $where = " AND {$typeFlag[$type]} BETWEEN '{$begin_date}' AND '{$end_date}'";
                }

            } else {
                Cm::$res->error('请传入时间区间');
            }
        }

        if ($type=='clean_user') {
            //$where .= "AND (unsubscribe IS NULL || unsubscribe <= '{$begin_date}' || unsubscribe >= '{$end_date}')";
            $where .= "AND (unsubscribe IS NULL || unsubscribe <= '{$begin_date}' || unsubscribe >= '{$end_date}') and is_new_add=0";
        }
        if (!empty($user_source)) {
            $value = $this->getSubscribeSceneTotal($user_source);
            $where .= " and subscribe_scene_type = {$value} ";
            $user_source = $user_source;
        } else {
            $user_source = null;
        }

        if (!in_array($type, ['new_user','cancel_user','clean_user','cumulate_user'])) {
            Cm::$res->error('请传入统计数据类型');
        }

        $date = $this->getDateFromRange($begin_date, $end_date);

        $sourceData = [];
        if ($date && is_array($date)) {
            foreach ($date as $v) {
                $sourceData[$v] = 0;
            }
        }

        $sql = "SELECT count(*) as num, FROM_UNIXTIME(UNIX_TIMESTAMP({$typeFlag[$type]}),'%Y-%m-%d') as subscribe
            FROM `scrm_weixin_customer` WHERE wx_account_id='{$this->wx_account_id}' {$where} GROUP BY FROM_UNIXTIME(UNIX_TIMESTAMP({$typeFlag[$type]}),'%Y-%m-%d')";
        if ($type=='cumulate_user') {
            $sql = "SELECT {$typeFlag[$type]},
            (
            SELECT
            SUM(num)
            FROM
            ({$sql}) AS test_table_1
            WHERE
            test_table_1.{$typeFlag[$type]} <= test_table_2.{$typeFlag[$type]}
            ) AS num
            FROM
            ({$sql}) AS test_table_2";
        }
        //var_dump($sql);exit;
        $result = Cm::$db->all($sql);

        $typeArray = [
            'new_user'=>'新增的用户数量',
            'cancel_user'=>'取消关注的用户数量',
            'clean_user'=>'净增用户数量',
            'cumulate_user'=>'总用户量'
        ];

        $list = [];
        if ($result && is_array($result)) {
            $list = $this->_array_column($result, 'num', 'subscribe');
        }



        $newList = ArrayHelper::merge($sourceData, $list);
        $resultList = [];
        $resultArray = [];
        if ($newList && is_array($newList)) {
            foreach ($newList as $k=>$item) {
                $resultList[] = [
                    "num"=>$item,
                    'date'=>$k,
                    'time'=>strtotime($k),
                ];
            }
            //排序
            array_multisort($this->_array_column($resultList,'time'), SORT_ASC, $resultList);
            //累计数据
            if ($type=='cumulate_user') {
                foreach ($resultList as $k=>$v) {
                    if (isset($v['num']) && (int)$v['num']===0) {
                        if ((int)$k-1 >=0) {
                            if (isset($resultArray[$k-1]['num'])) {
                                $temp = [
                                    "num"=>$resultArray[$k-1]['num'],
                                    'date'=>$v['date'],
                                    'time'=>$v['time'],
                                ];
                            } else {
                                $temp = [
                                    "num"=>0,
                                    'date'=>$v['date'],
                                    'time'=>$v['time'],
                                ];
                            }
                        } else {
                            $temp = $v;
                        }
                    } else {
                        $temp = $v;
                    }
                    $resultArray[] = $temp;
                }
            } else {
                $resultArray = $resultList;
            }
            //去除不存在时间段的统计总数
            $newStart = substr($begin_date, 0, strlen(date('Y-m-d')));
            if (!empty($resultArray) && is_array($resultArray)) {
                foreach ($resultArray as $k=>$v) {
                    if (strtotime($v['date']) < strtotime($newStart)) {
                        unset($resultArray[$k]);
                    }
                }
            }

            $data = [
                'type'=>$type,
                'type_remark'=>$typeArray[$type],
                'list'=>array_values($resultArray),
            ];
            $data['total'] = $this->getUserTotal($begin_date,$end_date,$user_source);

        }
        Cm::$res->susess('success', $data);
    }

    public function getUserTotal($begin_date, $end_date, $user_source='')
    {
        $begin_date = date('Y-m-d 00:00:00', strtotime($begin_date));
        $end_date = date('Y-m-d 23:59:59', strtotime($end_date));
        $typeFlag = [
            'new_user'=>'subscribe',
            'cancel_user'=>'unsubscribe',
            'clean_user'=>'subscribe',
            'cumulate_user'=>'subscribe'
        ];

        $where = null;
        $list = [];
        foreach ($typeFlag as $k=>$v) {
            $begin_date = date('Y-m-d 00:00:00', strtotime($begin_date));
            $end_date = date('Y-m-d 23:59:59', strtotime($end_date));
            if ($begin_date && $end_date) {

                if ($k=='cumulate_user') {
                    $where = " AND {$v} <= '{$end_date}'";
                } else {
                    $where = " AND {$v} BETWEEN '{$begin_date}' AND '{$end_date}'";
                }
            }


            if ($k=='clean_user') {
                $where .= "AND (unsubscribe IS NULL || unsubscribe <= '{$begin_date}' || unsubscribe >= '{$end_date}') and is_new_add=0";
                //$where .= "AND (unsubscribe IS NULL || unsubscribe <= '{$begin_date}' || unsubscribe >= '{$end_date}')";
            }

            if (!empty($user_source)) {
                $value = $this->getSubscribeSceneTotal($user_source);
                $where .= " and subscribe_scene_type = {$value} ";
                $user_source = $user_source;
            }


            $sql = "SELECT count(*) as num
            FROM `scrm_weixin_customer` WHERE wx_account_id='{$this->wx_account_id}' {$where} ";

            $result = Cm::$db->one($sql);
            $list[$k] = isset($result['num'])  ? (int)$result['num'] : 0;
        }

        $list['percent'] = $this->getNewUserPercent($user_source);

        return $list;
    }

    public function getNewUserPercent($user_source)
    {
        $typeFlag = [
            'new_user'=>'subscribe',
            'cancel_user'=>'unsubscribe',
            'clean_user'=>'subscribe',
            'cumulate_user'=>'subscribe'
        ];

        $date = self::getDates();
        $list = [];
        foreach ($date as $k=>$value)
        {
            $temp = [];
            foreach ($typeFlag as $key=>$v) {
                $begin_date_s = date('Y-m-d 00:00:00', strtotime($value['s']['start']));
                $begin_date_e = date('Y-m-d 23:59:59', strtotime($value['s']['end']));

                $end_date_s = date('Y-m-d 00:00:00', strtotime($value['e']['start']));
                $end_date_e = date('Y-m-d 23:59:59', strtotime($value['e']['end']));

                $whereStart = null;
                if ($begin_date_s && $begin_date_e) {

                    if ($k=='cumulate_user') {
                        $whereStart = " AND {$v} <= '{$begin_date_e}'";
                    } else {
                        $whereStart = " AND {$v} BETWEEN '{$begin_date_s}' AND '{$begin_date_e}'";
                    }
                }


                if ($k=='clean_user') {
                    $whereStart .= "AND (unsubscribe IS NULL || unsubscribe <= '{$begin_date_s}' || unsubscribe >= '{$begin_date_e}') and is_new_add=0";
                    //$whereStart .= "AND (unsubscribe IS NULL || unsubscribe <= '{$begin_date_s}' || unsubscribe >= '{$begin_date_e}')";
                }

                if (!empty($user_source)) {
                    $value = $this->getSubscribeSceneTotal($user_source);
                    $whereStart .= " and subscribe_scene_type = {$value} ";
                }

                $whereEnd = null;
                if ($end_date_s && $end_date_e) {

                    if ($k=='cumulate_user') {
                        $whereEnd = " AND {$v} <= '{$end_date_e}'";
                    } else {
                        $whereEnd = " AND {$v} BETWEEN '{$end_date_s}' AND '{$end_date_e}'";
                    }
                }


                if ($k=='clean_user') {
                    $whereEnd .= "AND (unsubscribe IS NULL || unsubscribe <= '{$end_date_s}' || unsubscribe >= '{$end_date_e}') and is_new_add=0";
                   // $whereEnd .= "AND (unsubscribe IS NULL || unsubscribe <= '{$end_date_s}' || unsubscribe >= '{$end_date_e}')";
                }

                if (!empty($user_source)) {
                    $value = $this->getSubscribeSceneTotal($user_source);
                    $whereEnd .= " and subscribe_scene_type = {$value} ";
                }


                $sqlStart = "SELECT count(*) as num
            FROM `scrm_weixin_customer` WHERE wx_account_id='{$this->wx_account_id}' {$whereStart} ";

                $sqlEnd = "SELECT count(*) as num
            FROM `scrm_weixin_customer` WHERE wx_account_id='{$this->wx_account_id}' {$whereEnd} ";

                $resultStart = Cm::$db->one($sqlStart);
                $startNum = isset($resultStart['num']) ? (int)$resultStart['num'] : 0;
                $resultEnd = Cm::$db->one($sqlEnd);
                $endNum = isset($resultEnd['num']) ? (int)$resultEnd['num'] : 0;
                $prcent = $endNum===0 ? 0 : round((float)$startNum/$endNum, 2);

                $temp[$key] = $prcent;
            }

           $list[$k] = $temp;
        }

        $listData = [];
        foreach ($list as $k=>$v) {
            $listData ['new_user'][$k]=$v['new_user'];
            $listData ['cancel_user'][$k]=$v['cancel_user'];
            $listData ['clean_user'][$k]=$v['clean_user'];
            $listData ['cumulate_user'][$k]=$v['cumulate_user'];
        }
        return $listData;
    }
    /**
     * 获取指定日期段内每一天的日期
     * @param  Date  $startdate 开始日期
     * @param  Date  $enddate   结束日期
     * @return Array
     */
    function getDateFromRange($startdate, $enddate){

        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);

        // 计算日期段内有多少天
        $days = ($etimestamp-$stimestamp)/86400+1;

        // 保存每天日期
        $date = array();

        for($i=0; $i<$days; $i++){
            $date[] = date('Y-m-d', $stimestamp+(86400*$i));
        }

        return $date;
    }


    public function totalUser($appid, $begin_date, $end_date,$source,$field, $where='')
    {

        $typeFlag = [
            'new_user'=>'subscribe',
            'cancel_user'=>'unsubscribe',
            'clean_user'=>'subscribe',
            'cumulate_user'=>'subscribe'
        ];

        $sql = "SELECT count(*) as num
            FROM `scrm_weixin_customer` WHERE wx_account_id='{$this->wx_account_id}' {$where} ";

        $sql = "SELECT 
            IFNULL(sum(u.new_user), 0) as new_user, IFNULL(sum(u.cancel_user), 0) as cancel_user, 
            IFNULL(sum(u.clean_user),0) as clean_user
            FROM `scrm_weixin_user_count` as u 
            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
            WHERE a.accountappid= '{$appid}'  AND u.date BETWEEN '{$begin_date}' AND '{$end_date}'";

        $sqlTwo = "SELECT u.cumulate_user
            FROM `scrm_weixin_user_count` as u 
            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
            WHERE a.accountappid= '{$appid}'  AND u.date = '{$end_date}'";
        $result = Cm::$db->one($sql);
        $resultTotal = Cm::$db->one($sqlTwo);
        if (!$result) {
            $result = [];
        }

        $result['percent'] = $this->getUserPercent($appid);
        if ($resultTotal) {
            $result['cumulate_user']=  $resultTotal['cumulate_user'];
        } else {
            $result['cumulate_user'] = 0;
        }

        return $result;
    }
    public function actionUserTotal()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);
        $begin_date = Cm::$req->post('begin_date', ['reg'=>'/^\d{4}-\d{2}-\d{2}/', 'title'=>'开始时间']);
        $end_date = Cm::$req->post('end_date', ['reg'=>'/^\d{4}-\d{2}-\d{2}/', 'title'=>'结束时间']);
        $sql = "SELECT 
            u.wx_account_id,a.accountappid, 
            IFNULL(sum(u.new_user), 0) as new_user, IFNULL(sum(u.cancel_user), 0) as cancel_user, 
            IFNULL(sum(u.clean_user),0) as clean_user
            FROM `scrm_weixin_user_count` as u 
            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
            WHERE a.accountappid= '{$appid}'  AND u.date BETWEEN '{$begin_date}' AND '{$end_date}'";

        $sqlTwo = "SELECT u.cumulate_user
            FROM `scrm_weixin_user_count` as u 
            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
            WHERE a.accountappid= '{$appid}'  AND u.date ='{$end_date}' ";
        $result = Cm::$db->one($sql);
        $resultTotal = Cm::$db->one($sqlTwo);
        if (!$result) {
            $result = [];
        }

        $result['percent'] = $this->getUserPercent($appid);
        if ($resultTotal) {
            $result['cumulate_user']=  $resultTotal['cumulate_user'];
        } else {
            $result['cumulate_user'] = 0;
        }
        Cm::$res->susess('success', $result);
    }

    /**
     * 获取比例数据：
     */
    public function getUserPercent($appid)
    {
        $date = self::getDates();
        $list = [];
        foreach ($date as $k=>$value) {
            $sql = "SELECT 
            u.wx_account_id,a.accountappid, 
            IFNULL(sum(u.new_user), 0) as new_user, IFNULL(sum(u.cancel_user), 0) as cancel_user, 
            IFNULL(sum(u.clean_user),0) as clean_user
            FROM `scrm_weixin_user_count` as u 
            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
            WHERE a.accountappid= '{$appid}' AND u.date BETWEEN '{$value['s']['start']}' AND '{$value['s']['end']}'";

            $sqlEnd = "SELECT 
            u.wx_account_id,a.accountappid, 
            IFNULL(sum(u.new_user), 0) as new_user, IFNULL(sum(u.cancel_user), 0) as cancel_user, 
            IFNULL(sum(u.clean_user),0) as clean_user
            FROM `scrm_weixin_user_count` as u 
            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
            WHERE a.accountappid= '{$appid}' AND u.date BETWEEN '{$value['e']['start']}' AND '{$value['e']['end']}'";

            $totalDate = substr($value['s']['end'], 0, strlen(date('Y-m-d')));
            $sqlTotal = "SELECT IFNULL(u.cumulate_user, 0) as cumulate_user
            FROM `scrm_weixin_user_count` as u 
            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
            WHERE a.accountappid= '{$appid}' AND  u.date  like '%{$totalDate}%' ";

            $totalEndDate = substr($value['e']['end'], 0, strlen(date('Y-m-d')));
            $sqlTotalEnd = "SELECT IFNULL(u.cumulate_user, 0) as cumulate_user
            FROM `scrm_weixin_user_count` as u 
            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
            WHERE a.accountappid= '{$appid}' AND  u.date like '%{$totalEndDate}%' ";
            $startResult = Cm::$db->one($sql);
            $endResult = Cm::$db->one($sqlEnd);


            if ($startResult && $endResult) {
                $data = [
                    'new_user'=>isset($endResult['new_user']) && !empty($endResult['new_user']) ? round($startResult['new_user']/$endResult['new_user'],2) : 0,
                    'cancel_user'=>isset($endResult['cancel_user']) && !empty($endResult['cancel_user']) ? round($startResult['cancel_user']/$endResult['cancel_user'],2) : 0,
                    'clean_user'=>isset($endResult['clean_user']) && !empty($endResult['clean_user']) ? round($startResult['clean_user']/$endResult['clean_user'],2) : 0,
                ];
            } else {
                $data = [
                    'new_user'=>0,
                    'cancel_user'=>0,
                    'clean_user'=>0,
                ];
            }

            $totalStart = Cm::$db->one($sqlTotal);
            $totalEnd = Cm::$db->one($sqlTotalEnd);
            if ($totalStart && $totalEnd) {
                $data['cumulate_user'] = isset($totalEnd['cumulate_user']) && !empty($totalEnd['cumulate_user']) ? round($totalStart['cumulate_user']/$totalEnd['cumulate_user'],2) : 0;
            } else {
                $data['cumulate_user'] = 0;
            }
            $list[$k] = $data;
        }
        //开始组装数据

        $listData = [];
        foreach ($list as $k=>$v) {
            $listData ['new_user'][$k]=$v['new_user'];
            $listData ['cancel_user'][$k]=$v['cancel_user'];
            $listData ['clean_user'][$k]=$v['clean_user'];
            $listData ['cumulate_user'][$k]=$v['cumulate_user'];
        }
        return $listData;
    }

    public function actionMessageReport()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);
        $begin_date = Cm::$req->post('begin_date', ['reg'=>'/^\d{4}-\d{2}-\d{2}/', 'title'=>'开始时间', 'null', 'empty', 'default'=>null]);
        $end_date = Cm::$req->post('end_date', ['reg'=>'/^\d{4}-\d{2}-\d{2}/', 'title'=>'结束时间', 'null', 'empty', 'default'=>null]);
        $type = Cm::$req->post('type', ['reg'=>'/[a-z_]+/', 'title'=>'统计类型','null','empty','default'=>0]);

        if (!empty($begin_date)) {
            if (strtotime($begin_date) > time()) {
                Cm::$res->error('开始时间小于当前时间');
            }
            if (!empty($end_date)) {
                if (strtotime($end_date) > time()) {
                    Cm::$res->error('结束时间小于当前时间');
                }
            } else {
                Cm::$res->error('请传入结束时间');
            }
        }
        $where = '';
        if (!empty($type)) {
            $where = " and m.msg_type={$type}";
        }
        $sql = "SELECT m.wx_account_id,a.accountappid,sum(m.msg_user) as msg_user, sum(m.msg_count) as msg_count
                FROM `scrm_weixin_message_count` m
                inner JOIN scrm_weixin_account a on m.wx_account_id=a.id
                WHERE a.accountappid= '{$appid}' {$where}";

        $result = Cm::$db->one($sql);
        if (!$result) {
            $result = [];
        }
        Cm::$res->susess('success', $result);
    }

    public function actionUseHomeReport()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);

        $date = $this->getDate('nearly_a_week');
        $begin_date = $date['start'];
        $end_date = $date['end'];

        $result = $this->getUserTotal($begin_date, $end_date);

        if (!$result) {
            $list = [
                'new_user'=>0,
                'cancel_user'=>0,
                'clean_user'=>0,
                'cumulate_user'=>0,
            ];
        } else {
            $list = [
                'new_user'=>(int)$result['new_user'],
                'cancel_user'=>(int)$result['cancel_user'],
                'clean_user'=>(int)$result['clean_user'],
                'cumulate_user'=>(int)$result['cumulate_user'],
            ];
        }

//        $sqlTwo = "SELECT u.cumulate_user
//            FROM `scrm_weixin_user_count` as u
//            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
//            WHERE a.accountappid= '{$appid}' order by date desc ";
//
//        $resultTotal = Cm::$db->one($sqlTwo);
//
//        $sql = "SELECT
//            u.wx_account_id,a.accountappid,
//            IFNULL(sum(u.new_user), 0) as new_user, IFNULL(sum(u.cancel_user), 0) as cancel_user,
//            IFNULL(sum(u.clean_user),0) as clean_user
//            FROM `scrm_weixin_user_count` as u
//            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
//            WHERE a.accountappid= '{$appid}'";
//        $result = Cm::$db->one($sql);
//        $result['cumulate_user'] = 0;
//        if (isset($resultTotal['cumulate_user'])) {
//            $result['cumulate_user'] = $resultTotal['cumulate_user'];
//        }
//
//        $date = self::getDate();
//
//        $list = [];
//        foreach ($date as $k=>$v) {
//            $sql = "SELECT
//            IFNULL(sum(u.new_user), 0) as new_user, IFNULL(sum(u.cancel_user), 0) as cancel_user,
//            IFNULL(sum(u.clean_user),0) as clean_user
//            FROM `scrm_weixin_user_count` as u
//            inner JOIN scrm_weixin_account a on u.wx_account_id=a.id
//            WHERE a.accountappid= '{$appid}' AND u.date between '{$v['start']}' AND '{$v['end']}'";
//            $temp = Cm::$db->one($sql);
//            if ($temp)
//                $list[$k] = $temp;
//        }
//        $result['list'] = $list;

        $list['wx_account_id'] = $this->wx_account_id;
        Cm::$res->susess('success', $list);
    }

    /**
     * 同步素材数据
     */
    public function actionSyncMaterial()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);


        $wechat=  new wxAction($appid);

        $sql= "select *from `scrm_weixin_fover_material_count` where wx_account_id='{$wechat->wx_app_data_id}'";
        $count = Cm::$db->one($sql);

        if ($count && $count['update_time'] > time()) {
            $wxCount =[
                'voice_count'=>$count['voice_count'],
                'video_count'=>$count['video_count'],
                'image_count'=>$count['image_count'],
                'news_count'=>$count['news_count'],
            ];
        } else {
            $wxCount = $wechat->getForeverCount();
            if (!$wxCount) {
                return false;
            } else {
                $dataCount = [
                    // 'wx_account_id'=>$wechat->wx_app_data_id,
                    'voice_count'=>$wxCount['voice_count'],
                    'video_count'=>$wxCount['video_count'],
                    'image_count'=>$wxCount['image_count'],
                    'news_count'=>$wxCount['news_count'],
                    //'update_time'=>'',
                ];
                if ($count) {
                    Cm::$db->update('scrm_weixin_fover_material_count', $dataCount, "wx_account_id='{$wechat->wx_app_data_id}'");
                } else {
                    $dataCount['id'] = (new CreateUuid())->toString();
                    $dataCount['update_time'] = time()+24*3600;
                    $dataCount['wx_account_id'] = $wechat->wx_app_data_id;
                    Cm::$db->insert('scrm_weixin_fover_material_count', $dataCount);
                }
            }
        }


        if (!empty($wxCount) && is_array($wxCount)) {
            ksort($wxCount);
            foreach ($wxCount as $k=>$value) {
                $function = 'sync'.ucfirst(substr($k,0, -6));
                if (!method_exists($this, $function)) {
                    continue;
                }
                $this->$function($appid, (int)$value);
            }
        }
        //开始执行查询数据：
        Cm::$res->susess('素材同步成功！');
    }

    //同步图片
    public function syncImage($appid, $count=0)
    {
        $page_size = 20;#每次回去数据
        $wechat = new wxAction($appid);
        //循环次数
        $end = ceil($count/$page_size);

        $image = Cm::$db->one("SELECT image_start,image_sync_time FROM `scrm_weixin_fover_material` where wx_account_id='{$wechat->wx_app_data_id}' and `type`='image' order by add_time desc " );

        if ($image) {
            $i = (int)$image['image_start'];

            if (strtotime(date('Y-m-d'))==$image['image_sync_time']){
                return true;
            }
        } else {
            $i = 1;
        }


        //开始计算数据：
        while ($i <= $end) {
            $start = ($i-1)*20+1;
            $result = $wechat->getForeverList('image', $start, $page_size);
            if ($result && isset($result['item']) && !empty($result['item'])) {
                foreach ($result['item'] as $v) {
                    $data = [
                        'wx_account_id'=>$wechat->wx_app_data_id,
                        'type'=>'image',
                        'title'=>$v['name'],
                        'media_id'=>$v['media_id'],
                        'url'=>$v['url'],
                        'update_time'=>date('Y-m-d H:i:s', $v['update_time']),
                        'image_start'=>$start,
                        'image_sync_time'=>strtotime(date('Y-m-d'))
                    ];
                    //add_time
                    $meterial = Cm::$db->one("select id from `scrm_weixin_fover_material` where wx_account_id='{$wechat->wx_app_data_id}' and `type`='image' and media_id='{$v['media_id']}'");
                    if ($meterial) {
                        Cm::$db->update('scrm_weixin_fover_material', $data, "id='{$meterial['id']}'");
                    } else {
                        $data['id'] = (new CreateUuid())->toString();
                        $data['add_time'] = date('Y-m-d H:i:s');
                        Cm::$db->insert('scrm_weixin_fover_material', $data);
                    }
                }
            } else {
                continue;
            }
            $i++;
        }
        return true;
    }
    //同步语音
    public function syncVoice($appid, $count=0)
    {
        $page_size = 20;#每次回去数据
        $wechat = new wxAction($appid);
        //循环次数
        $end = ceil($count/$page_size);

        $image = Cm::$db->one("SELECT voice_start,voice_sync_time FROM `scrm_weixin_fover_material` where wx_account_id='{$wechat->wx_app_data_id}' and `type`='voice' order by add_time desc " );
        if ($image) {
            $i = (int)$image['voice_start'];

            if (strtotime(date('Y-m-d'))==$image['voice_sync_time']){
                return true;
            }
        } else {
            $i = 1;
        }
        //开始计算数据：
        while ($i <= $end) {
            $start = ($i-1)*20+1;
            $result = $wechat->getForeverList('voice', $start, $page_size);
            if ($result && isset($result['item']) && !empty($result['item'])) {
                foreach ($result['item'] as $v) {
                    $data = [
                        'wx_account_id'=>$wechat->wx_app_data_id,
                        'type'=>'voice',
                        'title'=>$v['name'],
                        'media_id'=>$v['media_id'],
                        'url'=>$v['url'],
                        'update_time'=>date('Y-m-d H:i:s', $v['update_time']),
                        'voice_start'=>$start,
                        'voice_sync_time'=>strtotime(date('Y-m-d'))
                    ];
                    //add_time
                    $meterial = Cm::$db->one("select id from `scrm_weixin_fover_material` where wx_account_id='{$wechat->wx_app_data_id}' and `type`='voice' and media_id='{$v['media_id']}'");
                    if ($meterial) {
                        Cm::$db->update('scrm_weixin_fover_material', $data, "id='{$meterial['id']}'");
                    } else {
                        $data['id'] = (new CreateUuid())->toString();
                        $data['add_time'] = date('Y-m-d H:i:s');
                        Cm::$db->insert('scrm_weixin_fover_material', $data);
                    }
                }
            } else {
                continue;
            }

            $i++;
        }
        return true;
    }
    //同步视频
    public function syncVideo($appid, $count=0)
    {
        $page_size = 20;#每次回去数据
        $wechat = new wxAction($appid);
        //循环次数
        $end = ceil($count/$page_size);

        $image = Cm::$db->one("SELECT video_start,video_sync_time FROM `scrm_weixin_fover_material` where wx_account_id='{$wechat->wx_app_data_id}' and `type`='video' order by add_time desc " );

        if ($image) {
            $i = (int)$image['video_start'];

            if (strtotime(date('Y-m-d'))==$image['video_sync_time']){
                return true;
            }
        } else {
            $i = 1;
        }



        //开始计算数据：
        while ($i <= $end) {
            $start = ($i-1)*20+1;
            $result = $wechat->getForeverList('video', $start, $page_size);
            if ($result && isset($result['item']) && !empty($result['item'])) {
                foreach ($result['item'] as $v) {
                    $data = [
                        'wx_account_id'=>$wechat->wx_app_data_id,
                        'type'=>'video',
                        'title'=>$v['name'],
                        'media_id'=>$v['media_id'],
                        //'url'=>$v['url'],
                        'update_time'=>date('Y-m-d H:i:s', $v['update_time']),
                        'video_start'=>$start,
                        'video_sync_time'=>strtotime(date('Y-m-d'))
                    ];
                    if (isset($v['url'])) {
                        $data['utl']  = $v['url'];
                    }
                    //add_time
                    $meterial = Cm::$db->one("select id from `scrm_weixin_fover_material` where wx_account_id='{$wechat->wx_app_data_id}' and `type`='video' and media_id='{$v['media_id']}'");
                    if ($meterial) {
                        Cm::$db->update('scrm_weixin_fover_material', $data, "id='{$meterial['id']}'");
                    } else {
                        $data['id'] = (new CreateUuid())->toString();
                        $data['add_time'] = date('Y-m-d H:i:s');
                        Cm::$db->insert('scrm_weixin_fover_material', $data);
                    }
                }


            } else {
                continue;
            }

            $i++;
        }
        return true;
    }
    //同步多图文
    public function syncNews($appid, $count=0)
    {
        $page_size = 20;#每次回去数据
        $wechat = new wxAction($appid);
        //循环次数
        $end = ceil($count/$page_size);

        $image = Cm::$db->one("SELECT news_start,news_sync_time FROM `scrm_weixin_fover_material` where wx_account_id='{$wechat->wx_app_data_id}' and `type`='news' order by add_time desc " );



        if ($image) {
            $i = (int)$image['news_start'];

            if (strtotime(date('Y-m-d'))==$image['news_sync_time']){
                return true;
            }
        } else {
            $i = 1;
        }

        //开始计算数据：
        while ($i <= $end) {
            $start = ($i-1)*20+1;

            $result = $wechat->getForeverList('news', $start, $page_size);

            if ($result && isset($result['item']) && !empty($result['item'])) {
                foreach ($result['item'] as $v) {

                    $data = [
                        'wx_account_id'=>$wechat->wx_app_data_id,
                        'type'=>'news',
                        'media_id'=>$v['media_id'],
                        'update_time'=>date('Y-m-d H:i:s', $v['update_time']),
                        'news_start'=>$start,
                        'news_sync_time'=>strtotime(date('Y-m-d'))
                    ];

                    $meterial = Cm::$db->one("select id from `scrm_weixin_fover_material` where wx_account_id='{$wechat->wx_app_data_id}' and `type`='news' AND media_id='{$v['media_id']}'");

                    $material_id = '';
                    if ($meterial) {
                        $material_id = $meterial['id'];

                        Cm::$db->update('scrm_weixin_fover_material', $data, "id='{$material_id}'");
                    } else {
                        $material_id = (new CreateUuid())->toString();
                        $data['id'] = $material_id;
                        $data['add_time'] = date('Y-m-d H:i:s');
                        Cm::$db->insert('scrm_weixin_fover_material', $data);
                    }

                    $meterialInsert = Cm::$db->one("select id from `scrm_weixin_fover_material` where id='{$material_id}'");

                    if ($material_id && $meterialInsert) {

                        if (isset($v['content']['news_item']) && !empty($v['content']['news_item']) && is_array($v['content']['news_item'])) {
                            foreach ($v['content']['news_item'] as $item) {

                                if (isset($item['thumb_media_id']) && !empty($item['thumb_media_id'])) {
                                    $items = [
                                        'material_id'=>$material_id,
                                        'title'=>$item['title'],
                                        'thumb_media_id'=>$item['thumb_media_id'],
                                        'show_cover_pic'=>$item['show_cover_pic'],
                                        'author'=>$item['author'],
                                        'digest'=>$item['digest'],
                                        'content'=>$item['content'],
                                        'content_source_url'=>$item['content_source_url'],
                                        'url'=>$item['url'],
                                        'thumb_url'=>$item['thumb_url'],
                                        'need_open_comment'=>$item['need_open_comment'],
                                        'only_fans_can_comment'=>$item['only_fans_can_comment'],
                                        'update_time'=>date('Y-m-d H:i:s', $v['content']['update_time']),
                                        'create_time'=>date('Y-m-d H:i:s', $v['content']['create_time']),
                                    ];

                                    //add_time
                                    $meterial_items = Cm::$db->one("select id from `scrm_weixin_fover_material_items` where material_id='{$material_id}'");
                                    if ($meterial_items) {
                                        Cm::$db->update('scrm_weixin_fover_material_items', $items, "id='{$meterial_items['id']}'");
                                    } else {
                                        $items['id'] = (new CreateUuid())->toString();
                                        Cm::$db->insert('scrm_weixin_fover_material_items', $items);
                                    }
                                } else {
                                    continue;
                                }

                            }
                        }
                    }
                }
            } else {
                continue;
            }

            $i++;
        }
    }

    /**
     * 统计首页其他数据
     */
    public function actionUserHomeTotal()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);
        $msg = Cm::$db->one("SELECT count(*) as num  FROM `scrm_weixin_group_message_log` WHERE wx_account_id='{$this->wx_account_id}'");
        $article =  Cm::$db->one("SELECT count(*) as num FROM `scrm_weixin_article` WHERE wx_account_id='{$this->wx_account_id}' and del_flag=0");
        $template =  Cm::$db->one("SELECT count(*) as num FROM `scrm_weixin_template` WHERE wx_account_id='{$this->wx_app_id}' and  del_flag=0");
        $material =  Cm::$db->one("SELECT count(*) as num FROM `scrm_weixin_fover_material` WHERE wx_account_id='{$this->wx_account_id}' and status=0 and type in ('image', 'news')" );
        $msgNum = isset($msg['num']) ? $msg['num'] : 0;
        $articleNum = isset($article['num']) ? $article['num'] : 0;
        $templateNum = isset($template['num']) ? $template['num'] : 0;
        $materialNum = isset($material['num']) ? $material['num'] : 0;

        Cm::$res->susess('success', [
            'msg'=>$msgNum,
            'article'=>$articleNum,
            'template'=>$templateNum,
            'material'=>$materialNum,
            'total'=>$this->totalMarketing()
        ]);
    }

    /**
     * 首页图文阅读，分享统计
     * @return array|false
     */
    public function totalMarketing()
    {
        //发布的文章
        //and del_flag=0
        $article =  Cm::$db->one("SELECT count(*) as num FROM `scrm_weixin_article` WHERE wx_account_id='{$this->wx_account_id}'  and status=1");
        //群发的图文
        $groupHair =  Cm::$db->one("SELECT count(*) as num FROM `scrm_weixin_group_message_log` WHERE wx_account_id='{$this->wx_account_id}' and msg_type='news'  and status=1");
        //发布的微信模板
        $template =  Cm::$db->one("SELECT count(*) as num FROM `scrm_weixin_template_send_log` WHERE wx_account_id='{$this->wx_account_id}' and msg_type='news'  and status=1");
        //发布量
        $total = (int)$article['num']+(int)$groupHair['num']+(int)$template['num'];
        $sum = Cm::$db->one("SELECT 
        IFNULL(sum(page_read_count), 0) as page_read_count,
        IFNULL(sum(page_read_user), 0) as page_read_user,
        IFNULL(sum(share_user), 0) as share_user,
        IFNULL(sum(share_count), 0) as share_count 
        FROM `scrm_weixin_article_count` 
        WHERE wx_account_id='{$this->wx_account_id}'");

        if (!$sum) {
            $sum = [
                'page_read_count'=>0,
                'page_read_user'=>0,
                'share_user'=>0,
                'share_count'=>0,
            ];
        }

        $sum['release_volume'] = $total;

        return $sum;
    }
}